<template>
	<PageTemplate title="发布">
    <template #default>
      <view class="publish-container">
        <!-- 发布卡片 -->
        <view class="publish-card">
          <!-- 用户信息区域 -->
          <view class="user-info-section">
            <image 
              :src="userInfo.avatar" 
              class="user-avatar" 
              mode="aspectFill"
            />
            <view class="user-info">
              <text class="user-name">{{ userInfo.name || '用户' }}</text>
              <text class="user-status">分享生活点滴...</text>
            </view>
            <button 
              class="publish-btn small" 
              @click="submitPublish"
              :disabled="isSubmitting"
            >
              {{ isSubmitting ? '发布中...' : '发布' }}
            </button>
          </view>
          
          <!-- 内容输入区域 -->
          <view class="content-input-section">
            <textarea 
              class="content-input" 
              placeholder="分享你的生活..." 
              v-model="publishContent"
              maxlength="200"
            />
            <view class="char-count">
              {{ publishContent.length }}/200
            </view>
          </view>
        </view>
        
        <!-- 媒体选择卡片 -->
        <view class="publish-card media-card">
          <view class="media-section">
            <view class="section-header">
              <text class="section-title">添加照片</text>
              <text class="media-count">{{ selectedImages.length }}/9</text>
            </view>
            <view class="media-grid">
              <view 
                class="media-item" 
                v-for="(image, index) in selectedImages" 
                :key="index"
              >
                <image 
                  :src="image" 
                  mode="aspectFill" 
                  class="media-image"
                />
                <view class="remove-overlay" @click="removeImage(index)">
                  <text class="remove-icon">✕</text>
                </view>
              </view>
              
              <view 
                class="add-media-btn" 
                @click="chooseImage"
                v-if="selectedImages.length < 9"
              >
                <text class="add-icon">+</text>
                <text class="add-text">添加照片</text>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 设置卡片 -->
        <view class="publish-card settings-card">
          <view class="settings-section">
            <view class="setting-item">
              <view class="setting-info">
                <text class="setting-label">公开可见</text>
              </view>
              <switch 
                :checked="privacyIndex === 0" 
                @change="onPrivacyChange"
                color="#00C874"
              />
            </view>
            <view class="setting-description">开启后，所有人可以看到这条动态</view>
          </view>
        </view>
      </view>
    </template>
  </PageTemplate>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { onUnload } from '@dcloudio/uni-app'
import { createPublish } from '@/api/publish/index.ts'
import { uploadFile } from '@/utils/upload.ts'
import { showToast, getUserInfo, navigateTo } from '@/utils/index.ts'
import PageHeader from '@/components/PageHeader.vue';
import PageTemplate from '@/components/PageTemplate.vue';

const publishContent = ref('')
const selectedImages = ref([])
const privacyIndex = ref(0)
const isSubmitting = ref(false)

// 用户信息
const userInfo = reactive({
	name: '',
	avatar: ''
})

// 页面加载时获取用户信息
onMounted(() => {
	const storedUserInfo = getUserInfo()
	if (storedUserInfo) {
		userInfo.name = storedUserInfo.name
		userInfo.avatar = storedUserInfo.avatar
	}
})

// 选择图片
const chooseImage = () => {
	uni.chooseImage({
		count: 9 - selectedImages.value.length,
		success: (res) => {
			selectedImages.value = [...selectedImages.value, ...res.tempFilePaths]
		},
		fail: (err) => {
			console.error('取消选择图片:', err)
			showToast('取消选择图片')
		}
	})
}

// 移除图片
const removeImage = (index) => {
	selectedImages.value.splice(index, 1)
}

// 清除所有内容
const clearAll = () => {
	publishContent.value = ''
	selectedImages.value = []
	privacyIndex.value = 0
}

// 隐私设置变更
const onPrivacyChange = (e) => {
	privacyIndex.value = e.detail.value ? 0 : 1
}

// 提交发布
const submitPublish = async () => {
	if (!publishContent.value.trim() && selectedImages.value.length === 0) {
		showToast('请输入内容或选择图片')
		return
	}
	
	isSubmitting.value = true
	
	try {
		// 上传图片并获取图片ID
		const imageIds = []
		for (const imagePath of selectedImages.value) {
			try {
				const uploadResult = await uploadFile(imagePath)
				if (uploadResult.code === 200) {
					imageIds.push(uploadResult.data.upload_id)
				}
			} catch (error) {
				console.error('上传图片失败:', error)
				return
			}
		}
		
		// 提交发布内容
		const publishData = {
			content: publishContent.value,
			image_ids: imageIds,
			privacy: privacyIndex.value === 0 ? 1 : 0 // 1公开 0私密
		}
		
		const res = await createPublish(publishData)
    
    if (res.code === 200) {
      showToast('发布成功', 'success')
      clearAll()
      
      // 发布成功后返回首页
      uni.$emit('switchTab', 0)
    }
	} catch (error) {
		console.error('发布失败:', error)
	} finally {
		isSubmitting.value = false
	}
}

// 页面卸载时重置状态
onUnload(() => {
	isSubmitting.value = false
})
</script>
<style scoped>

.publish-container {
	padding: 0 30rpx 30rpx;
}

.publish-card {
	background: #ffffff;
	border-radius: 20rpx;
	box-shadow: 0 6rpx 15rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	transition: all 0.3s ease;
}

.publish-card:hover {
	box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.1);
	transform: translateY(-2rpx);
}

.user-info-section {
	display: flex;
	align-items: center;
	padding: 30rpx;
	border-bottom: 1rpx solid #eee;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
	border: 2rpx solid #ffffff;
	box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
}

.user-info {
	flex: 1;
}

.user-name {
	font-size: 32rpx;
	font-weight: 600;
	color: #2c3e50;
	display: block;
}

.user-status {
	font-size: 24rpx;
	color: #999;
}

.publish-btn.small {
  width: auto;
  min-width: 100rpx;
  height: 52rpx;
  border-radius: 26rpx;
  font-size: 24rpx;
  font-weight: 500;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  transition: all 0.3s ease;
  padding: 0 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  background: linear-gradient(90deg, #007aff, #00c874);
  color: #fff;
  margin: 0;
}

.publish-btn.small:active {
  transform: scale(0.96);
}

.publish-btn.small:disabled {
  background: #cccccc;
  color: #999999;
  box-shadow: none;
  transform: none;
}

.content-input-section {
	padding: 30rpx;
}

.content-input {
	width: 100%;
	min-height: 300rpx;
	font-size: 32rpx;
	line-height: 1.6;
	color: #333;
	border: none;
	outline: none;
	resize: none;
	background-color: transparent;
}

.char-count {
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin-top: 20rpx;
}

.media-section {
	padding: 30rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20rpx;
}

.section-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #2c3e50;
}

.media-count {
	font-size: 24rpx;
	color: #999;
}

.media-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 15rpx;
}

.media-item {
	position: relative;
	width: 100%;
	aspect-ratio: 1/1;
	border-radius: 12rpx;
	overflow: hidden;
}

.media-image {
	width: 100%;
	height: 100%;
}

.remove-overlay {
	position: absolute;
	top: 0;
	right: 0;
	left: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	opacity: 0;
	transition: opacity 0.3s ease;
}

.media-item:hover .remove-overlay,
.media-item:active .remove-overlay {
	opacity: 1;
}

.remove-icon {
	color: #ffffff;
	font-size: 50rpx;
	font-weight: bold;
}

.add-media-btn {
	width: 100%;
	aspect-ratio: 1/1;
	border: 2rpx dashed #d9d9d9;
	border-radius: 12rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.3s ease;
	background-color: #fafafa;
}

.add-media-btn:hover,
.add-media-btn:active {
	border-color: #007aff;
	background-color: #f0f8ff;
}

.add-icon {
	font-size: 60rpx;
	color: #007aff;
	font-weight: 300;
}

.add-text {
	font-size: 24rpx;
	color: #007aff;
	margin-top: 10rpx;
}

.media-card {
  margin-top: 20rpx;
}

.settings-card {
  margin-top: 20rpx;
}

.settings-section {
	padding: 30rpx;
	border-top: none;
}

.setting-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
}

.setting-info {
	flex: 1;
}

.setting-label {
	display: block;
	font-size: 30rpx;
	color: #2c3e50;
	font-weight: 500;
}

.setting-description {
	font-size: 24rpx;
	color: #999;
	line-height: 1.4;
	padding: 0 30rpx 30rpx 30rpx;
}
</style>